package middleware

import (
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils/jwt"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

func AuthorizeRpa(excludes []string) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 1. 排除鉴权的路由
		if utils.InArray(excludes, ctx.Request.URL.Path) {
			ctx.Next()
			return
		}

		token := ctx.Request.Header.Get("rpa_token")
		if token == "" {
			token = ctx.DefaultQuery("rpa_token", "")
			if token == "" {
				response(ctx, errcode.COMMON_USER_IDENTITY_ERROR, "缺少访问令牌")
				return
			}
		}

		tokenClaim, err := jwt.DefaultRpaJWT.ParseRpaToken(token)
		if err != nil {
			stark.Logger.Infof(ctx, "AuthorizeRpa-err: %+v, token: %s", err, token)
			response(ctx, errcode.COMMON_TOKEN_ERROR, "令牌解析错误")
			return
		}

		ctx.Set(jwt.RPA_AUTH_INFO, tokenClaim)
		ctx.Next()
	}
}
